<template>
  <div class="creator">
    <TopHeader :show-more="false" :show-share="false" @back="emits('toPage', 2, 'profile')"></TopHeader>
    <div class="personal bg-background">
      <div class="bg">
        <EncryptImage
          :src="previewImage.background_img || profile.background_img"
          object-fit="cover"
          click-to-full
        ></EncryptImage>
      </div>
      <div class="content">
        <AvatarContainer :avatar="previewImage.avatar || profile.avatar" :vip="isVip">
          <template #buttons>
            <button class="primary-btn personal-btn" @click="() => uploadAvatar.click()">
              {{ $t('info.upload.avatar') }}
            </button>
            <button class="primary-btn personal-btn" @click="() => uploadBackground.click()">
              {{ $t('info.upload.background') }}
            </button>
          </template>
        </AvatarContainer>
        <input
          ref="uploadAvatar"
          type="file"
          accept="image/jpg, image/jpeg, image/png, image/gif"
          @change="onImageLoad"
          hidden
        />
        <input
          ref="uploadBackground"
          type="file"
          accept="image/jpg, image/jpeg, image/png, image/gif"
          @change="onUploadBackground"
          hidden
        />
        <div class="form">
          <div class="text-primary font-size-12 font-weight-400 line-height-120 gap-col-4 py-2">
            <div>{{ $t('info.avatar.size') }}</div>
            <div>{{ $t('info.bg.size') }}</div>
          </div>
          <InputWrap
            v-model="profile.displayName.value"
            :err-msg="profile.displayName.error"
            :label="$t('label.displayName')"
            :placeholder="$t('placeholder.displayName')"
            disabled
          ></InputWrap>
          <InputWrap
            v-model="profile.username.value"
            :err-msg="profile.username.error"
            :label="$t('label.username')"
            :placeholder="$t('placeholder.username')"
            class="mt-4"
            disabled
          ></InputWrap>
          <TextareaWrap
            v-model="profile.description.value"
            :err-msg="profile.description.error"
            :label="$t('label.description')"
            :placeholder="$t('placeholder.description')"
            class="mt-4"
          ></TextareaWrap>
          <div class="mt-2">
            <SocialButton
              v-if="profile.socialLink.instagram?.value"
              :label="profile.socialLink.instagram?.value"
              append-icon="deleteAcc"
              prepend-icon="instagram"
              @click="() => (profile.socialLink.instagram.value = '')"
            ></SocialButton>
          </div>
          <div class="mt-2">
            <SocialButton
              v-if="profile.socialLink.twitter?.value"
              :label="profile.socialLink.twitter?.value"
              append-icon="deleteAcc"
              prepend-icon="twitter"
              @click="() => (profile.socialLink.twitter.value = '')"
            ></SocialButton>
          </div>
          <div class="mt-2">
            <SocialButton
              v-if="profile.socialLink.tiktok?.value"
              :label="profile.socialLink.tiktok?.value"
              append-icon="deleteAcc"
              prepend-icon="tiktok"
              @click="() => (profile.socialLink.tiktok.value = '')"
            ></SocialButton>
          </div>
          <div class="mt-2">
            <SocialButton
              v-if="profile.socialLink.vida?.value"
              :label="profile.socialLink.vida?.value"
              append-icon="deleteAcc"
              prepend-icon="vida"
              @click="() => (profile.socialLink.vida.value = '')"
            ></SocialButton>
          </div>
          <div class="mt-2">
            <SocialButton :label="$t('label.socialLink')" @click="openSocialLink"></SocialButton>
          </div>
          <InputWrap
            v-model="profile.amount.value"
            class="mt-4"
            type="number"
            :label="$t('label.subscribeFee')"
            :placeholder="$t('placeholder.defaultSubscribeFee')"
            :number="true"
            :err-msg="profile.amount.error"
            input-mode="decimal"
          ></InputWrap>
          <div class="between mt-4">
            <div class="text-white font-size-14 font-style-normal font-weight-500 line-height-140">
              {{ $t('label.subscribeSetting') }}
            </div>
            <InputSwitch :inputBg="'defaultBg'" v-model="profile.subscription"></InputSwitch>
          </div>
          <v-divider class="mt-6"></v-divider>
          <div class="d-flex gap-row-16 mt-4">
            <div
              class="cancel-light-btn w-100 d-flex justify-center align-center"
              @click="emits('toPage', 2, 'profile')"
            >
              <button :disabled="isLoading">{{ $t('common.cancel') }}</button>
            </div>
            <div class="primary-btn w-100 d-flex justify-center align-center" @click="onExecute(onSave)">
              <button :disabled="isLoading">
                <CircularLoading
                  v-if="isLoading"
                  size="20"
                  weight="2.5"
                  color="grayscale"
                  duration="1"
                  type="solid"
                ></CircularLoading>
                <span v-else>{{ $t('common.save') }}</span>
              </button>
            </div>
          </div>
          <div v-if="saveErrMsg" class="text-start err-msg font-size-14 font-weight-400 line-height-120 text-primary-x">
            {{ saveErrMsg }}
          </div>
        </div>
      </div>
    </div>
    <div class="tail-size-96"></div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useAccountStore } from '@/store/account'
import { useAppStore } from '@/store/app'
import { usePopupDialogStore } from '@/store/popup-dialog'
import { $t } from '@/i18n'
import { useYup, validate } from '@/plugins/yup'
import SocialButton from '@/components/button/SocialButton.vue'
import CircularLoading from '@/components/common/CircularLoading.vue'
import InputSwitch from '@/components/form/InputSwitch.vue'
import InputWrap from '@/components/form/InputWrap.vue'
import TextareaWrap from '@/components/form/TextareaWrap.vue'
import AvatarContainer from '@/components/layout/creator/AvatarContainer.vue'
import TopHeader from '@/components/layout/creator/TopHeader.vue'
import EncryptImage from '@/components/multimedia/EncryptImage.vue'
import useCutImage from '@/compositions/dialog/cut-image'
import { useExecutionLock } from '@/compositions/utils'
import { POPUP_DIALOG_TYPE } from '@/constant'
import API from '@/http'
import { upload } from '@/http/upload/uploadImage'

const accountStore = useAccountStore()
const { userData, isVip } = storeToRefs(accountStore)
const { refetchUserDetail } = accountStore

const { appConfig } = useAppStore()

const profile = reactive({
  background_img: userData.value.background_img,
  avatar: userData.value.avatar,
  displayName: {
    value: userData.value.nickname,
    error: '',
    check: false,
  },
  username: {
    value: userData.value.username,
    error: '',
    check: false,
  },
  description: {
    value: userData.value.bio,
    error: '',
    check: false,
  },
  amount: {
    value: parseFloat(userData.value.subscribe_price) ?? null,
    error: '',
    check: false,
  },
  socialLink: {
    instagram: {
      value: userData.value.link_instagram,
    },
    tiktok: {
      value: userData.value.link_tiktok,
    },
    twitter: {
      value: userData.value.link_twitter,
    },
    vida: {
      value: userData.value.link_vida,
    },
  },
  subscription: userData.value.subscribe_button,
  uploadAvatar: '',
  uploadBackground: '',
})

const previewImage = reactive({
  avatar: '',
  background_img: '',
})

const saveErrMsg = ref('')

const { $popupDialog } = usePopupDialogStore()
const openSocialLink = () => {
  $popupDialog(POPUP_DIALOG_TYPE.SOCIAL_LINK, {
    title: $t('title.socialLink'),
    confirm: (data) => {
      console.table(data)
      profile.socialLink = data
    },
    confirmText: $t('common.save'),
    content: profile.socialLink,
  }).open()
}

const uploadAvatar = ref(null)
const uploadBackground = ref(null)

const { onImageLoad } = useCutImage({
  inputRef: uploadAvatar,
  onFinish: async (newAvatarUrl) => {
    previewImage.avatar = newAvatarUrl
    await refetchUserDetail()
  },
})

const onUploadBackground = async (e) => {
  try {
    profile.uploadBackground = await upload(e.target.files[0])
    previewImage.background_img = appConfig.config.img_url + profile.uploadBackground
    await API.Auth.update({ data: { background_img: profile.uploadBackground } })
    await refetchUserDetail()
  } catch (e) {
    console.error(e)
  }
}

const Yup = useYup()
const displayNameSchema = Yup.string().required().min(2).max(50)
const usernameSchema = Yup.string()
  .required()
  .min(4)
  .max(50)
  .matches(/^[\w+_]*$/)
const descriptionSchema = Yup.string().max(500)
const amountSchema = Yup.number()
  .min(0.99)
  .nullable(true)
  .transform((_, val) => (val === Number(val) ? val : null))

const { onExecute, disabled: isLoading } = useExecutionLock()

const onSave = async () => {
  const _displayNameValidate = await validate(displayNameSchema, profile.displayName)
  const _usernameValidate = await validate(usernameSchema, profile.username)
  const _descriptionValidate = await validate(descriptionSchema, profile.description)
  const _amountValidate = await validate(amountSchema, profile.amount)

  if (!_displayNameValidate || !_usernameValidate || !_descriptionValidate || !_amountValidate) return
  await saveProfile()
}

const emits = defineEmits(['toPage'])

const saveProfile = async () => {
  try {
    const data = {
      // TODO 暫時先關閉
      // username: profile.username.value,
      // nickname: profile.displayName.value,
      bio: profile.description.value,
      // 沒有設置就給0.99
      subscribe_price: profile.amount.value || 0.99,
      subscribe_button: profile.subscription ? 1 : 0,
    }
    if (profile.socialLink.instagram?.value) data.link_instagram = profile.socialLink.instagram.value
    if (profile.socialLink.tiktok?.value) data.link_tiktok = profile.socialLink.tiktok.value
    if (profile.socialLink.twitter?.value) data.link_twitter = profile.socialLink.twitter.value
    if (profile.socialLink.vida?.value) data.link_vida = profile.socialLink.vida.value

    await API.Auth.update({ data })
    await refetchUserDetail()
    emits('toPage', 2, 'profile')
    saveErrMsg.value = ''
  } catch (e) {
    console.error(e)
    saveErrMsg.value = e.message
  }
}
</script>

<style lang="scss" scoped>
.creator {
  width: 100%;
  height: 100%;
  position: relative;
  margin-bottom: 6rem;
  overflow-x: hidden;
}

.personal {
  width: 100%;
  min-height: 100%;

  .bg {
    width: 100%;
    height: 9.5625rem;
    color: mediumorchid;
    background-color: cadetblue;
  }

  .content {
    height: calc(100% - 40.8vw + 2.5rem);
    transform: translateY(-2.5rem);
  }
}
.form {
  padding: 1rem;
}

.between {
  width: 100%;
  display: flex;
  align-items: center;
  align-content: center;
  justify-content: space-between;
  align-self: stretch;
}
</style>
